package com.hzz.web.boss.examine;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.hzz.api.examine.IExamineResultAttachService;
import com.hzz.api.examine.IExamineResultDetailService;
import com.hzz.api.examine.IExamineResultService;
import com.hzz.api.examine.IExamineTargetDetailService;
import com.hzz.api.examine.IExamineTargetService;
import com.hzz.dto.examine.ExamineResultAttachDto;
import com.hzz.dto.examine.ExamineResultDetailDto;
import com.hzz.dto.examine.ExamineResultDto;
import com.hzz.dto.examine.ExamineTargetDetailDto;
import com.hzz.dto.examine.ExamineTargetDto;
import com.hzz.dto.user.UserDto;
import com.hzz.framework.PageUtil;
import com.hzz.framework.Response;
import com.hzz.framework.annotation.ALogOperation;
import com.hzz.framework.annotation.RfUser2Bean;
import com.hzz.framework.annotation.auth.Logical;
import com.hzz.framework.annotation.auth.RequiresPermissions;
import com.hzz.framework.util.CommonConstant;
import com.hzz.framework.util.JwtUtil;
import com.hzz.framework.web.controller.BaseController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Api(description = "目标考核-考核结果")
@RestController
@Slf4j
public class ExamineResultController extends BaseController {
	@Autowired
	IExamineResultService examineResultService;
	@Autowired
	IExamineResultDetailService examineResultDetailService;
	@Autowired
	IExamineTargetDetailService examineTargetDetailService;
	@Autowired
	IExamineTargetService examineTargetService;
	@Autowired
	IExamineResultAttachService examineResultAttachService;
	static final String acPrefix = "/boss/examine/examineResult/";

	@RequiresPermissions("examineResult:menu")
	@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }, value = acPrefix + "page/{pageNum}")
	// @ApiOperation(value = "信息分页(未删除)")
	public Response page(@ModelAttribute ExamineResultDto dto, @PathVariable("pageNum") Integer pageNum) {
		log.info("page.........");
		Response result = new Response();
		try {
			dto.setPageSize(CommonConstant.PAGEROW_DEFAULT_COUNT);
			dto.setPageNum(pageNum);
			dto.setDelFlag(0);
			result.data = PageUtil.copy(examineResultService.findDataIsPage(dto));
		} catch (Exception e) {
			result = Response.error(e.getMessage());
		}
		return result;
	}

	@RequiresPermissions("examineResult:info")
	@RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "info/{id}")
	// @ApiOperation(value = "信息详情")
	public Response info(@PathVariable("id") Long id) {
		log.info("info.........");
		Response result = new Response();
		try {
			ExamineResultDto dto = new ExamineResultDto();
			dto.setId(id);
			dto.setDelFlag(0);
			result.data = examineResultService.findDataById(dto);
		} catch (Exception e) {
			result = Response.error(e.getMessage());
		}
		return result;
	}

	@RequiresPermissions("examineResult:del")
	@RequestMapping(method = RequestMethod.POST, value = acPrefix + "del/{id}")
	@ALogOperation(type = "删除", desc = "目标考核-考核结果-逻辑删除")
	// @ApiOperation(value = "逻辑删除")
	public Response del(@PathVariable("id") Long id) {
		log.info("del.........");
		Response result = new Response(0, "success");
		try {
			ExamineResultDto dto = new ExamineResultDto();
			dto.setId(id);
			result.message = examineResultService.deleteDataById(dto);
		} catch (Exception e) {
			result = Response.error(e.getMessage());
		}
		return result;
	}

	@RequiresPermissions(value = { "examineResult:add", "examineResult:edit" }, logical = Logical.OR)
	@RequestMapping(method = { RequestMethod.POST, RequestMethod.PUT }, value = acPrefix + "save")
	@RfUser2Bean
	@ALogOperation(type = "修改", desc = "目标考核-考核结果")
	// @ApiOperation(value = "信息保存")
	public Response save(@Validated @RequestBody ExamineResultDto dto, BindingResult bindingResult) {
		log.info("save.........");
		Response result = new Response(0, "success");
		try {
			// if ("1".equals(request.getSession().getAttribute(acPrefix +
			// "save." + dto.getToken()))) {
			// throw new RuntimeException("请不要重复提交!");
			// }
			if (bindingResult.hasErrors()) {
				String errorMsg = "";
				List<ObjectError> errorList = bindingResult.getAllErrors();
				for (ObjectError error : errorList) {
					errorMsg += (error.getDefaultMessage()) + ";";
				}
				result = Response.error(errorMsg);
			} else {
				result = examineResultService.saveOrUpdateData(dto);
				// request.getSession().setAttribute(acPrefix + "save." +
				// dto.getToken(), "1");
			}
		} catch (Exception e) {
			result = Response.error(e.getMessage());
		}
		return result;
	}

	// @RequiresPermissions("examineResult:info")
	@RequestMapping(method = RequestMethod.GET, value = acPrefix + "getResults")
	@ApiOperation(value = "根据河长ID及评估ID查询考核结果信息")
	public Response getResults(@ModelAttribute ExamineResultDto dto) {
		log.info("info.........");
		Response result = new Response();
		try {
			ExamineResultDto resultDto = getResultDto(dto);
			// 查询结果明细
			ExamineResultDetailDto resultDetailDto = new ExamineResultDetailDto();
			resultDetailDto.setResultId(resultDto.getId());
			List<ExamineResultDetailDto> resultDetails = examineResultDetailService.findDataIsList(resultDetailDto);
			resultDto.setResultDetails(resultDetails);
			// 查询考核目标
			ExamineTargetDto targetDto = new ExamineTargetDto();
			targetDto.setId(resultDto.getTargetId());
			resultDto.setTarget(examineTargetService.findDataById(targetDto));
			// 查询考核目标明细
			ExamineTargetDetailDto targetDetailDto = new ExamineTargetDetailDto();
			targetDetailDto.setTargetId(resultDto.getTargetId());
			List<ExamineTargetDetailDto> targetDetails = this.examineTargetDetailService
					.findDataIsList(targetDetailDto);
			resultDto.setTargetDetails(targetDetails);
			// 查询附件
			ExamineResultAttachDto attachDto = new ExamineResultAttachDto();
			attachDto.setResultId(resultDto.getId());
			List<ExamineResultAttachDto> attachs = this.examineResultAttachService.findDataIsList(attachDto);
			resultDto.setAttachs(attachs);

			result.data = resultDto;
		} catch (Exception e) {
			result = Response.error(e.getMessage());
		}
		return result;
	}

	/**
	 * 查询考核结果
	 * 
	 * @param dto
	 * @return
	 * @throws Exception
	 */
	private ExamineResultDto getResultDto(ExamineResultDto dto) throws Exception {
		if (dto.getId() != null) {// 如果有ID就用ID查
			return this.examineResultService.findDataById(dto);
		} else if (dto.getEvaluateId() != null) {// 否则用当前用户+评估ID查
			UserDto user = JwtUtil.getSubject(UserDto.class);
			dto.setUserId(user.getId());
			List<ExamineResultDto> list = examineResultService.findDataIsList(dto);
			if (list != null && !list.isEmpty()) {
				return list.get(0);// 正常情况下只有一条数据
			}
		}
		throw new NullPointerException("未获取到考核结果信息");
	}

	@RequiresPermissions("examineLeaderEvaluation:menu")
	@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }, value = acPrefix
			+ "findJuniorDataIsPage/{pageNum}")
	@ApiOperation(value = "查询下级考核结果信息分页(未删除)")
	public Response findJuniorDataIsPage(@ModelAttribute ExamineResultDto dto,
			@PathVariable("pageNum") Integer pageNum) {
		log.info("findJuniorDataIsPage.........");
		Response result = new Response();
		try {
			dto.setPageSize(CommonConstant.PAGEROW_DEFAULT_COUNT);
			dto.setPageNum(pageNum);
			dto.setDelFlag(0);
			UserDto user = JwtUtil.getSubject(UserDto.class);
			dto.setCurrAreaId(user.getCurrAreaId());
			dto.setUserId(user.getId());
			result.data = PageUtil.copy(examineResultService.findJuniorDataIsPage(dto));
		} catch (Exception e) {
			result = Response.error(e.getMessage());
		}
		return result;
	}

	@RequiresPermissions("examineLeaderEvaluation:edit")
	@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }, value = acPrefix + "updateLeaderScore")
	@ApiOperation(value = "保存上级领导评分")
	public Response updateLeaderScore(@RequestBody ExamineResultDto dto) {
		log.info("updateLeaderScore.........");
		Response result = new Response();
		try {
			result = examineResultService.updateLeaderScore(dto);
		} catch (Exception e) {
			result = Response.error(e.getMessage());
		}
		return result;
	}
}